<script type="module" setup>

//引入模块
import { reactive } from 'vue'
//准备购物车数据,设置成响应数据
const carts = reactive([{ name: '可乐', price: 3, number: 10 }, { name: '薯片', price: 6, number: 8 }])

//计算购物车总金额
function compute() {
    let count = 0;
    for (let index in carts) {
        count += carts[index].price * carts[index].number;
    }
    return count;
}
//删除购物项方法
function removeCart(index) {
    carts.splice(index, 1);//从给定的索引位置开始删除一个或多个元素
}
//删除所有购物项方法
function removeAll() {
    carts.splice(0, carts.length); //从索引0开始删除所有元素
}
</script>

<template>
    <div>
        <table border="1" cellspacing="0" cellpadding="10">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>商品名</th>
                    <th>价格</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody v-if="carts.length > 0">
                <tr v-for="(cart, index) in carts" :key="index">
                    <td>{{ index + 1 }}</td>
                    <td>{{ cart.name }}</td>
                    <td>{{ cart.price }}</td>
                    <td>{{ cart.number }}</td>
                    <td>{{ cart.price * cart.number }}</td>
                    <td><button @click="removeCart(index)">删除</button></td>
                </tr>
            </tbody>
            <tbody v-else>
                <tr>
                    <td colspan="6">购物车空空如也</td>
                </tr>
            </tbody>
        </table>
        <button @click="removeAll()">清空购物车</button>
        <h2>购物车总金额: {{ compute() }}</h2>
    </div>
</template>